<template>
  <div class="module-container">
    <h2>客户信息</h2>
    <div class="module-content">
      <div class="search-container">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="请输入客户姓名或ID"
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <button @click="handleSearch" class="search-button">搜索</button>
          <button @click="goToCreatePage" class="create-button">创建客户</button>
          <button 
            @click="showBatchDeleteDialog = true"
            class="batch-delete-button"
            :disabled="selectedCustomers.length === 0"
          >
            批量删除<span v-if="selectedCustomers.length > 0"> ({{ selectedCustomers.length }})</span>
          </button>
        </div>
        <!-- 客户类型筛选按钮 -->
        <div class="filter-container">
          <div class="filter-buttons">
            <button 
              v-for="type in customerTypes" 
              :key="type.id"
              :class="['filter-button', { active: selectedCustomerType === type.id }]"
              @click="selectCustomerType(type.id)"
            >
              {{ type.name }} ({{ type.count }})
            </button>
          </div>
        </div>
      </div>
      
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>
                <input 
                  type="checkbox" 
                  :checked="areAllCustomersSelected" 
                  @change="toggleSelectAll"
                />
              </th>
              <th v-for="column in columns" :key="column.key">{{ column.title }}</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in paginatedCustomers" :key="item.customerId || index">
              <td>
                <input 
                  type="checkbox" 
                  :checked="selectedCustomers.includes(item.customerId)"
                  @change="toggleCustomerSelection(item.customerId)"
                />
              </td>
              <td v-for="column in columns" :key="column.key">
                <template v-if="column.key === 'manager'">
                  {{ item[column.key] || '-' }}
                </template>
                <template v-else>
                  {{ item[column.key] }}
                </template>
              </td>
              <td>
                <button 
                  v-for="action in actions" 
                  :key="action.name"
                  :class="['action-button', action.type || 'default']"
                  @click="handleAction(action.name, item)"
                >
                  {{ action.label }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="pagination">
        <button 
          class="pagination-button" 
          :disabled="pagination.current <= 1"
          @click="handlePageChange(pagination.current - 1)"
        >
          上一页
        </button>
        <span class="pagination-info">第 {{ pagination.current }} 页，共 {{ Math.ceil(pagination.total / pagination.pageSize) }} 页</span>
        <button 
          class="pagination-button" 
          :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)"
          @click="handlePageChange(pagination.current + 1)"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
  
  <!-- 添加编辑客户弹窗 -->
  <EditCustomer 
    ref="editCustomerDialog"
    v-model:visible="editCustomerVisible"
    @success="handleEditSuccess"
  />
  
  <!-- 删除确认对话框 -->
  <el-dialog
    v-model="deleteDialogVisible"
    title="确认删除"
    width="300px"
  >
    <span>确定要删除客户 "{{ currentDeleteCustomer?.name }}" 吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 批量删除确认对话框 -->
  <el-dialog
    v-model="showBatchDeleteDialog"
    title="确认批量删除"
    width="300px"
  >
    <span v-if="selectedCustomers.length > 0">确定要删除选中的 {{ selectedCustomers.length }} 个客户吗？</span>
    <span v-else>请先选择要删除的客户</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showBatchDeleteDialog = false">取消</el-button>
        <el-button 
          v-if="selectedCustomers.length > 0"
          type="danger" 
          @click="confirmBatchDelete" 
          :loading="batchDeleteLoading"
        >
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import EditCustomer from './EditCustomer.vue'
import { getCustomerInfo, deleteCustomerInfo, deleteBatchCustomerInfo } from '@/apis/customer'
import { deleteCustomerPhone } from '@/apis/phoneNumber'
import { ElMessage } from 'element-plus'

export default {
  name: 'CustomerInfoTemplate',
  components: {
    EditCustomer
  },
  data() {
    return {
      searchQuery: '',
      selectedCustomerType: 'all',
      customerTypes: [
        { id: 'all', name: '所有客户', count: 0 },
        { id: '企业', name: '企业客户', count: 0 },
        { id: '个人', name: '个人客户', count: 0 }
      ],
      allCustomers: [],
      loading: false,
      deleteLoading: false,
      batchDeleteLoading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'customerId', title: '客户ID' },
        { key: 'name', title: '姓名' },
        { key: 'type', title: '类型' },
        { key: 'community', title: '社区' },
        { key: 'manager', title: '经理' },
        { key: 'specialist', title: '专员' },
        { key: 'communityManager', title: '社区经理' },
        { key: 'createTime', title: '创建时间' }
      ],
      actions: [
        { name: 'view', label: '查看', type: 'view' },
        { name: 'edit', label: '编辑', type: 'edit' },
        { name: 'delete', label: '删除', type: 'delete' }
      ],
      editCustomerVisible: false,
      deleteDialogVisible: false,
      showBatchDeleteDialog: false,
      currentEditCustomer: null,
      currentDeleteCustomer: null,
      selectedCustomers: [] // 存储选中项的ID
    }
  },
  computed: {
    // 分页后的客户数据
    paginatedCustomers() {
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.customers.slice(start, end);
    },
    customers() {
      // 根据选择的客户类型筛选客户
      let filteredCustomers = this.allCustomers;
      
      // 如果有搜索查询，先按搜索结果筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.trim().toLowerCase();
        filteredCustomers = filteredCustomers.filter(customer => 
          (customer.name && customer.name.toLowerCase().includes(query)) ||
          (customer.customerId && customer.customerId.toString().includes(query))
        );
      }
      
      // 再根据选择的客户类型筛选
      if (this.selectedCustomerType !== 'all') {
        filteredCustomers = filteredCustomers.filter(customer => 
          customer.type === this.selectedCustomerType
        );
      }
      
      return filteredCustomers;
    },
    // 检查是否所有客户都被选中
    areAllCustomersSelected() {
      return this.paginatedCustomers.length > 0 && 
             this.selectedCustomers.length === this.paginatedCustomers.length;
    }
  },
  methods: {
    async loadCustomerData() {
      this.loading = true;
      try {
        const res = await getCustomerInfo({
          offset: (this.pagination.current - 1) * this.pagination.pageSize,
          limit: this.pagination.pageSize,
          // 添加搜索参数
          searchQuery: this.searchQuery
        });
        console.log('客户数据:', res);
        // 根据后端接口返回的数据结构处理数据
        if (res && res.code === 0 && res.data) {
          // 使用后端返回的 records 数据
          this.allCustomers = res.data.records || [];
          this.pagination.total = res.data.total || 0;
          // 更新各类型客户的数量
          this.updateCustomerTypeCounts();
        }
      } catch (error) {
        console.error('获取客户数据失败:', error);
        // 出错时清空数据
        this.allCustomers = [];
      } finally {
        this.loading = false;
      }
    },
    updateCustomerTypeCounts() {
      // 计算各类型客户的数量
      const businessCount = this.allCustomers.filter(c => c.type === '企业').length;
      const individualCount = this.allCustomers.filter(c => c.type === '个人').length;
      
      this.customerTypes.find(t => t.id === '企业').count = businessCount;
      this.customerTypes.find(t => t.id === '个人').count = individualCount;
      this.customerTypes.find(t => t.id === 'all').count = this.allCustomers.length;
    },
    handleSearch() {
      console.log('搜索客户:', this.searchQuery);
      // 重置到第一页并重新加载数据
      this.pagination.current = 1;
      this.loadCustomerData();
    },
    selectCustomerType(typeId) {
      this.selectedCustomerType = typeId;
      // 清除选中项
      this.selectedCustomers = [];
      // 重新加载数据
      this.pagination.current = 1;
      this.loadCustomerData();
    },
    goToCreatePage() {
      this.$router.push('/customer/create');
    },
    handleAction(actionName, item) {
      switch (actionName) {
        case 'view':
          console.log('查看客户:', item);
          break;
        case 'edit':
          // 打开编辑弹窗
          this.currentEditCustomer = { ...item }; // 复制客户信息
          this.editCustomerVisible = true;
          this.$nextTick(() => {
            // 在下一次DOM更新后设置表单数据
            // 确保传递完整的客户信息，包括ID
            this.$refs.editCustomerDialog?.setFormData(this.currentEditCustomer);
          });
          break;
        case 'delete':
          // 打开删除确认对话框
          this.currentDeleteCustomer = { ...item };
          this.deleteDialogVisible = true;
          break;
      }
    },
    handlePageChange(page) {
      this.pagination.current = page;
      // 清除选中项
      this.selectedCustomers = [];
      this.loadCustomerData();
    },
    // 添加编辑成功回调
    handleEditSuccess() {
      // 重新加载客户数据
      this.loadCustomerData();
    },
    // 确认删除客户
    async confirmDelete() {
      if (!this.currentDeleteCustomer) return;
      
      this.deleteLoading = true;
      try {
        // 先删除客户与手机号的关联关系
        await deleteCustomerPhone(this.currentDeleteCustomer.customerId);
        
        // 再删除客户信息
        const res = await deleteCustomerInfo(this.currentDeleteCustomer.customerId);
        if (res && res.code === 0) {
          ElMessage.success('客户删除成功');
          // 关闭对话框
          this.deleteDialogVisible = false;
          // 重新加载数据
          this.loadCustomerData();
          // 清除选中项
          this.selectedCustomers = this.selectedCustomers.filter(
            id => id !== this.currentDeleteCustomer.customerId
          );
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除客户失败:', error);
        ElMessage.error('删除客户失败');
      } finally {
        this.deleteLoading = false;
      }
    },
    // 切换客户选择状态
    toggleCustomerSelection(customerId) {
      const index = this.selectedCustomers.indexOf(customerId);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedCustomers.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedCustomers.push(customerId);
      }
    },
    // 切换全选状态
    toggleSelectAll(event) {
      if (event.target.checked) {
        // 全选当前页的所有客户
        this.selectedCustomers = this.paginatedCustomers.map(customer => customer.customerId);
      } else {
        // 取消全选
        this.selectedCustomers = [];
      }
    },
    // 确认批量删除
    async confirmBatchDelete() {
      // 检查是否有选中的客户
      if (this.selectedCustomers.length === 0) {
        ElMessage.warning('请先选择要删除的客户');
        return;
      }
      
      this.batchDeleteLoading = true;
      try {
        // 先删除每个客户的关联关系
        for (const customerId of this.selectedCustomers) {
          await deleteCustomerPhone(customerId);
        }
        
        // 将选中的客户ID数组转换为逗号分隔的字符串
        const ids = this.selectedCustomers.join(',');
        const res = await deleteBatchCustomerInfo(ids);
        if (res && res.code === 0) {
          ElMessage.success('批量删除成功');
          // 关闭对话框
          this.showBatchDeleteDialog = false;
          // 清空选中项
          this.selectedCustomers = [];
          // 重新加载数据
          this.loadCustomerData();
        } else {
          ElMessage.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        console.error('批量删除客户失败:', error);
        ElMessage.error('批量删除客户失败');
      } finally {
        this.batchDeleteLoading = false;
      }
    }
  },
  mounted() {
    this.loadCustomerData();
  }
}
</script>

<style scoped>
@import '@/assets/global-module-styles.css';

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.create-button {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.create-button:hover {
  background-color: #218838;
}

.batch-delete-button {
  padding: 10px 20px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.batch-delete-button:hover {
  background-color: #c82333;
}

.filter-container {
  margin-top: 15px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-button {
  padding: 8px 16px;
  background-color: #e9ecef;
  color: #495057;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.filter-button:hover {
  background-color: #dee2e6;
}

.filter-button.active {
  background-color: #667eea;
  color: white;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>